//
//  SWTakePhotoViewController.swift
//  MiU
//
//  Created by linhan on 16/3/26.
//  Copyright © 2016年 MiU. All rights reserved.
//

import Foundation
import UIKit
import AVFoundation

protocol SWTakePhotoViewControllerDelegate:NSObjectProtocol
{
    func takePhotoViewController(_ viewController:SWTakePhotoViewController, didFinishPicking images:[UIImage])
}

class SWTakePhotoViewController: SWBaseViewController,SWStillCameraViewDelegate
{
    weak var delegate:SWTakePhotoViewControllerDelegate?
    
    //是否正在转换过程中
    private var _exchanging:Bool = false{
        didSet{
            _exchangeBtn.isEnabled = !_exchanging
        }
    }
    
    private var _capturing:Bool = false{
        didSet{
            _takePhotoBtn.isEnabled = !_capturing
        }
    }
    
    private var _photos:[SWCameraPhoto] = []
    
    private var _cameraView:SWStillCameraView = SWStillCameraView()
    
    private var _exchangeBtn:UIButton = UIButton(type:.custom)
    lazy private var _takePhotoBtn:UIButton = UIButton(type:.custom)
    lazy private var _soundBtn:UIButton = UIButton(type:.custom)
    lazy private var _albumView:UIImageView = UIImageView()
    
    private let _bottomView:UIView = UIView()
    
    
    deinit
    {
        
        trace("DEINIT SWTakePhotoViewController")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if appearedFirstTime
        {
            appearedFirstTime = false
            _cameraView.authAVCapture()
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        _soundBtn.isSelected = false
        setSoundBarVisible(show: false)
    }
    
    //隐藏导航栏
    override var prefersNavigationBarHidden: Bool{
        return true
    }
    
    //隐藏状态栏
    override var prefersStatusBarHidden:Bool {
        return true
    }
    
    func close()
    {
        //dispose()
        _cameraView.dispose()
        dismiss(animated:true, completion: nil)
    }
    
    private func setup()
    {
        view.backgroundColor = UIColor.black
        
        let closeBtn:UIButton = UIButton(type: .custom)
        closeBtn.setImage(UIImage(named: "editor_camera_btn_close"), for: .normal)
        closeBtn.sizeToTouchEasy()
        closeBtn.center = CGPointMake(22, 22)
        closeBtn.addTarget(self, action: #selector(closeBtnTapped), for: .touchUpInside)
        view.addSubview(closeBtn)
        
        _exchangeBtn.isHidden = true
        _exchangeBtn.setImage(UIImage(named: "editor_camera_btn_switch"), for: .normal)
        _exchangeBtn.sizeToTouchEasy()
        _exchangeBtn.center = CGPointMake(view.width - 22, 24)
        _exchangeBtn.addTarget(self, action: #selector(exchangeBtnTapped), for: .touchUpInside)
        view.addSubview(_exchangeBtn)
        
        _cameraView.delegate = self
        _cameraView.frame = CGRectMake(0, 44, view.frame.width, view.frame.width)
        view.addSubview(_cameraView)
        
        let bottomViewHeight:CGFloat = view.height - _cameraView.bottom
        _bottomView.frame = CGRectMake(0, view.height - bottomViewHeight, view.width, bottomViewHeight)
        view.addSubview(_bottomView)
        
        _takePhotoBtn.setImage(UIImage(named: "editor_camera_btn_takephoto"), for: .normal)
        _takePhotoBtn.setImage(UIImage(named: "editor_camera_btn_takephotoHL"), for: .highlighted)
        _takePhotoBtn.setImage(UIImage(named: "editor_camera_btn_takephotoHL"), for: .disabled)
        _takePhotoBtn.sizeToFit()
        _takePhotoBtn.isEnabled = false
        _takePhotoBtn.center = CGPointMake(_bottomView.width * 0.5, _bottomView.height - _takePhotoBtn.height * 0.5 - 53)
        _takePhotoBtn.addTarget(self, action: #selector(takePhotoBtnTapped), for: .touchUpInside)
        _bottomView.addSubview(_takePhotoBtn)
        
        //相册
        let albumViewSize = CGSizeMake(55, 55)
        let albumTapGesture = UITapGestureRecognizer(target: self, action: #selector(albumViewTapped))
        _albumView.backgroundColor = UIColor.black
        _albumView.frame = CGRectMake(30, _bottomView.height - albumViewSize.height - 53, albumViewSize.width, albumViewSize.height)
        _albumView.addGestureRecognizer(albumTapGesture)
        _albumView.contentMode = .scaleAspectFill
        _albumView.clipsToBounds = true
        _albumView.isUserInteractionEnabled = true
        _bottomView.addSubview(_albumView)
        
        //铃声
        _soundBtn.setImage(UIImage(named: "editor_camera_btn_sound"), for: .normal)
        _soundBtn.setImage(UIImage(named: "editor_camera_btn_soundHL"), for: .highlighted)
        _soundBtn.setImage(UIImage(named: "editor_camera_btn_soundHL"), for: .selected)
        _soundBtn.sizeToFit()
        _soundBtn.frame = CGRectMake(view.width - _soundBtn.width - 30, _bottomView.height - _soundBtn.height - 53, _soundBtn.width, _soundBtn.height)
        _soundBtn.addTarget(self, action: #selector(soundBtnTapped), for: .touchUpInside)
        _bottomView.addSubview(_soundBtn)
        
        loadLastPhotoThumb()
    }
    
    private func loadLastPhotoThumb()
    {
        var assets = SWAssetsManager.sharedManager().assets
        assets.sort(by: {$0.addedTime > $1.addedTime})
        if let localID:String = assets.flatMap({$0.localID}).filter({$0 != ""}).valueAt(0)
        {
            var options = SWALPhotoRequestOptions()
            options.targetSize = CGSizeMake(200, 200)
            SWAssetsLibraryHelper.shared().fetchOriginImage(localIdentifiers: [localID], options:options, completeCallback: {[weak self] results in
                if let result = results.valueAt(0),
                    let image = result.image
                {
                    self?._albumView.image = image
                }
            })
        }
    }
    
    private var _soundBar:SWCameraSoundBar?
    private func setSoundBarVisible(show:Bool)
    {
        if show
        {
            if _soundBar == nil
            {
                let soundBarHeight:CGFloat = 26
                let topMargin:CGFloat = 30
                let soundBar = SWCameraSoundBar(frame: CGRectMake(0, topMargin, view.width, soundBarHeight))
                _soundBar = soundBar
            }
            
            if let soundBar = _soundBar
            {
                _bottomView.addSubview(soundBar)
            }
        }
        else
        {
            SWSoundPlayer.stopAll()
            _soundBar?.deselect()
            _soundBar?.removeFromSuperview()
        }
        
    }
    
    func stillCameraAuthorizationDenied(_ cameraView:SWStillCameraView)
    {
        _bottomView.isHidden = true
    }
    
    func stillCameraLaunchComplete(_ cameraView:SWStillCameraView)
    {
        if cameraView.exchangeEnable
        {
            //_exchangeBtn = UIBarButtonItem(image: UIImage(named: "editor_camera_btn_switch"), style: .plain, target: self, action: #selector(exchangeBtnTapped))
            //navigationItem.rightBarButtonItem = _exchangeBtn
            _exchangeBtn.isHidden = false
        }
        
        _takePhotoBtn.isEnabled = true
    }
    
    func stillCameraWillBeginExchanging(_ cameraView:SWStillCameraView)
    {
        _exchanging = true
    }
    
    func stillCameraDidEndExchanging(_ cameraView:SWStillCameraView)
    {
        _exchanging = false
    }
    
    //开始截图
    func stillCameraWillBeginCapturing(_ cameraView:SWStillCameraView)
    {
        _capturing = true
    }
    
    func stillCameraDidEndCapturing(_ cameraView:SWStillCameraView, image:UIImage?, error:Error?)
    {
        self._capturing = false
        if let image = image
        {
            delegate?.takePhotoViewController(self, didFinishPicking: [image])
            let thumb:UIImage = Toucan.Resize.resizeImage(image, size: CGSizeMake(100, 100), fitMode: .crop)
            _albumView.image = thumb
        }
    }
    
    
    
    //MARK ============================================================================================
    //==============================        SWPhotoViewerDelegate       ===============================
    //=================================================================================================
    
    
    
    @objc private func takePhotoBtnTapped()
    {
        _cameraView.capture()
    }
    
    //前后摄像头切换
    @objc private func exchangeBtnTapped()
    {
        _cameraView.position = _cameraView.position == .back ? .front : .back
    }
    
    @objc private func closeBtnTapped()
    {
        close()
    }
    
    @objc private func soundBtnTapped()
    {
        _soundBtn.isSelected = !_soundBtn.isSelected
        setSoundBarVisible(show: _soundBtn.isSelected)
    }
    
    @objc private func albumViewTapped()
    {
        navigationController?.pushViewController(SWPhotosDetailViewController(), animated: true)
    }
    
}




